<template>
  <div
    :id="`code-editor`"
    ref="codeEditorRef"
    style="display: flex; min-height: 600px; min-width: 800px"
  ></div>
</template>
<script lang="ts" setup>
import * as monaco from "monaco-editor";
import { defineProps, onMounted, ref, toRaw, watch, withDefaults } from "vue";
// or import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
// if shipping only a subset of the features & languages is desired
const codeEditorRef = ref();
// 用于接收编译器
const codeEditor = ref();

interface Props {
  value: string;
  language: string;
  handleChange: (v: string) => void;
  readonly: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  value: () => "",
  language: () => "java",
  readonly: false,
  handleChange: (v: string) => {
    console.log(v);
  },
});

// 更新编译器
watch(
  () => props.language,
  () => {
    monaco.editor.setModelLanguage(
      // 踩坑一定要使用toRaw
      toRaw(codeEditor.value).getModel(),
      props.language
    );
  }
);

// 检查节点是否出现
onMounted(() => {
  if (!codeEditorRef.value) {
    return;
  }
  codeEditor.value = monaco.editor.create(codeEditorRef.value, {
    value: props.value,
    language: props.language,
    lineNumbers: "on",
    roundedSelection: false,
    scrollBeyondLastLine: false,
    readOnly: props.readonly,
    theme: "vs-dark",
    fontSize: 14, //字体大小
    quickSuggestionsDelay: 100, //代码提示延时
  });
  // 添加监听
  codeEditor.value.onDidChangeModelContent(() => {
    props.handleChange(toRaw(codeEditor.value).getValue());
  });
});

// 样式
</script>

<style scoped>
#code-editor {
  display: flex;
  min-height: 600px;
  min-width: 800px;
  width: 100%;
  height: 70vh;
}
</style>
